<template>
  <div class="app-container">
    <el-card class="filter-container" :style="{ marginBottom: '20px' }" :shadow="defaultData.cardShadow">
      <div class="operate-container">
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
        </div>
        <div>
          <el-button style="float: right" type="primary" @click="getList()">
            搜索
          </el-button>
          <el-button style="float: right; margin-right: 15px" @click="handleResetSearch()">
            重置
          </el-button>
        </div>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="powerfulTableData.listQuery">
          <div class="screenForm">
            <el-form-item label="用户名：">
              <el-input v-model="powerfulTableData.listQuery.name" placeholder="请输入用户名" clearable />
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>

    <el-card :shadow="defaultData.cardShadow">
      <div class="operate-container">
        <div>
          <i class="el-icon-tickets"></i>
          <span>数据列表</span>
        </div>

        <div>
          <el-button type="primary" class="btn-add" @click="handleAdd()">
            创建用户
          </el-button>
        </div>
      </div>

      <div>
        <PowerfulTable :list="powerfulTableData.list" :header="header" :isSelect="false" :property="property"
          :pagination-property="{
            total: powerfulTableData.total,
            pageSizes: [2, 5, 7],
          }" @size-change="getList" @component-event="handleComponentChange" @btn-click="handleBtnClick">
          <template #createTime="{ row }">
            <div>{{ formatTime(row.createTime) }}</div>
          </template>
          <template #updateTime="{ row }">
            <div>{{ formatTime(row.updateTime) }}</div>
          </template>
          <template #accountState="{ row }">
            <div>{{ row.accountState == 0 ? '停用' : '正常' }}</div>
          </template>
          <template #accountOwner="{ row }">
            <div>{{ row.accountOwner }}</div>
          </template>
          <template #accountType="{ row }">
            <div>{{ accountTypeMap.get(row.accountType) }}</div>
          </template>
        </PowerfulTable>
        <el-pagination v-model:current-page="powerfulTableData.listQuery.pageNum" class="pagination-container"
          v-model:page-size="powerfulTableData.listQuery.pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next" :total="powerfulTableData.total" @size-change="sizeChange"
          @current-change="getList" />
      </div>
    </el-card>
    <!-- 关联车型弹窗 -->
    <el-dialog title="关联车型" v-model="bindModelDialog" width="45%">
      <div>
        <el-form :model="bindModel" :rules="rules" ref="uploadForm" label-width="auto" class="Dform">
          <el-form-item label="品牌：" prop="brandUuid">
            <el-select v-model="bindModel.brandUuid" @change="getSeriesList" filterable clearable style="width: 100%"
              placeholder="请选择品牌">
              <el-option v-for="item in brandList" :key="item.brandUuid" :label="item.brandName"
                :value="item.brandUuid" />
            </el-select>
          </el-form-item>
          <el-form-item label="车系：" prop="seriesUuid">
            <el-select v-model="bindModel.seriesUuid" @change="getModelList" filterable clearable style="width: 100%"
              placeholder="请选择车系">
              <el-option v-for="item in seriesList" :key="item.seriesUuid" :label="item.seriesName"
                :value="item.seriesUuid" />
            </el-select>
          </el-form-item>
          <el-form-item label="车型：" prop="modelUuid">
            <el-select v-model="bindModel.modelUuid" filterable clearable style="width: 100%" placeholder="请选择车型">
              <el-option v-for="item in modelList" :key="item.modelUuid" :label="item.modelName"
                :value="item.modelUuid" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitBindModel()" style="margin-top: 15px">
              提交
            </el-button>
          </el-form-item>
        </el-form>
        <div>
          <h3>已关联车型：</h3>
          <div v-for="item in accountModel" :key="item.accountModelUuid" style="display: flex; align-items: center;">
            <div>
              {{ item.brandName }} {{ item.seriesName }} {{ item.modelName }}
            </div>
            <el-button type="danger" @click="removeBindModel(item.accountModelUuid)" style="margin-left: 10px;">
              删除
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 编辑区 -->
    <Update v-model:dialog="isDialog" v-if="isDialog" v-model:currentForm="currentForm" @refresh="getList" />
  </div>
</template>
<script lang="ts" setup>
import { accountQuery, removeAccount, accountModelQuery, saveAccountModel, removeAccountModel } from '@/api/user'
import { useData, Model, defaultData as defaultForm } from './indexData'
import { Handlers } from 'el-plus-powerful-table'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores'
import Update from './update.vue'
import { formatTime } from '@/utils'
import { brandQueryAll, selectListByBrandUuid, selectListBySeriesUuid, carQuery } from '@/api/vehicle'

import { property, accountTypeMap, } from '@/config/constants'
const { header, powerfulTableData, currentForm, isDialog } = useData()


const userStore = useUserStore()
const bindModelDialog = ref(false)
const data = ref<any>([])
const modelList = ref<any>([])
const seriesList = ref<any>([])
const brandList = ref<any>([])
const accountModel = ref<any>([])
const bindModel = reactive({
  accountUuid: '',
  seriesUuid: '',
  brandUuid: '',
  modelUuid: '',
})
// 获取用户列表
const getList = () => {
  accountQuery(powerfulTableData.listQuery).then((res) => {
    console.log(res)
    powerfulTableData.list = res.data.list
    powerfulTableData.total = res.data.total
  })
}

const removeBindModel = (accountModelUuid: string) => {
  removeAccountModel({ accountModelUuid }).then(() => {
    ElMessage.success('删除成功！')
    getAccountModel()
  })
}
// 分页大小改变
const sizeChange = (val: number) => {
  powerfulTableData.listQuery.pageSize = val
  getList()
}
getList()
const rules = reactive({
  brandUuid: [{ required: true, message: '请选择品牌', trigger: 'blur' }],
  seriesUuid: [{ required: true, message: '请选择车系', trigger: 'blur' }],
  modelUuid: [{ required: true, message: '请选择车型', trigger: 'blur' }],
})
const handleComponentChange: Handlers['component-event'] = (payload) => {
  switch (payload.componentName) {
    // 停用事件
    case 'switch':
      const e = payload.row
      if (userStore.userInfo.id == e.id && e.status === 0) {
        ElMessage.error('你的账号已被停用！')
      }
      break
  }
}

const handleAdd = () => {
  Object.assign(currentForm.value, defaultForm())
  isDialog.value = true;
}

const submitBindModel = () => {
  saveAccountModel(bindModel).then(() => {
    ElMessage.success('关联成功！')
    bindModelDialog.value = false
    bindModel.brandUuid = ''
    bindModel.seriesUuid = ''
    bindModel.modelUuid = ''
    // getBindModelList(currentForm.value.accountUuid)
  })
}

const getSeriesList = () => {
  bindModel.seriesUuid = ''
  bindModel.modelUuid = ''
  if (!bindModel.brandUuid) {
    return
  }
  selectListByBrandUuid({ pageNum: 1, pageSize: 100, brandUuid: bindModel.brandUuid }).then((res: any) => {
    seriesList.value = res.data || []
  })
}
const getAccountModel = () => {
  accountModelQuery({ accountUuid: bindModel.accountUuid, pageNum: 1, pageSize: 1000 }).then((res: any) => {
    accountModel.value = res.data.list || []
  })
}
const getBrandList = () => {
  brandQueryAll().then((res: any) => {
    brandList.value = res.data || []
  })
  getAccountModel()
}

const getModelList = () => {
  if (!bindModel.seriesUuid) {
    return
  }
  selectListBySeriesUuid({ pageNum: 1, pageSize: 100, seriesUuid: bindModel.seriesUuid }).then((res: any) => {
    modelList.value = res.data || []
  })
}

const handleBtnClick: Handlers['btn-click'] = ({ params, row }) => {
  console.log(row)
  switch (params) {
    case 'edit':
      isDialog.value = true;
      Object.assign(currentForm.value, JSON.parse(JSON.stringify(row)))
      break
    case 'bindModel':
      bindModelDialog.value = true;
      bindModel.accountUuid = row.accountUuid
      getBrandList()
      break
    case 'remove':
      remove(row)
      break
  }
}

const remove = (row: Model) => {
  ElMessageBox.confirm('是否确认删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    removeAccount({ accountUuid: row.accountUuid }).then(() => {
      ElMessage.success('删除成功！')
      getList()
    })
  })
}

const getBindModelList = (accountUuid: string) => {
  accountModelQuery({ accountUuid, pageNum: 1, pageSize: 1000 }).then((res) => {
    console.log(res)
    data.value = res.data.list || []
  })
}

// 分配菜单
const handleAddRole = () => {
  // switchs.role = false
  // powerfulTableData.list = powerfulTableData.list.map((item: RowType) => {
  //   if (item.id == (currentForm.value as RowType).id) {
  //     item = currentForm.value as RowType
  //   }
  //   return item
  // })
}

// 重置
const handleResetSearch = () => {
  Object.keys(powerfulTableData.listQuery).forEach((item: any) => {
    let arr = ['pageNum', 'pageSize']
    if (arr.indexOf(item) == -1) {
      ; (powerfulTableData.listQuery as { [s: string]: string | number })[item] =
        ''
    }
  })
  getList()
}
</script>
<style scoped>
:deep(.el-transfer-panel) {
  width: 230px;
}
</style>
